package client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Semaphore;

import decode.DecodeMessage;

import utils.Utils;

import file.BufferMap;
import file.CoupleIpPort;
import file.File;

/**
 * 
 */

/**
 * @author acidflow
 *
 */
public class UpdatePeers implements Runnable {

	private File _file;
	private Thread _thread;
	private long _intervalle;
	private Semaphore _semaphore; 
	
	public UpdatePeers(File f, long inter, Semaphore sem){
		_file = f;
		_intervalle = inter;
		_semaphore = sem;
		_thread = new Thread(this, "Update Peers");
		_thread.start();
	}
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		while(true){
			try {
				
				String bm = new String(_file.getBufferMap().toByteArray(), "ISO-8859-1");
				String message = "have "+ _file.getIdFile() + " " + bm;
				
				_semaphore.acquire(_file.getPeers().size());
				for(CoupleIpPort cp : _file.getPeers()){
					Socket s = new Socket(cp.getIp(), cp.getPort());
					s.getOutputStream().write(message.getBytes("ISO-8859-1"));
					String response = DecodeMessage.decodeMessageFromSocket(s.getInputStream(), "client", _file);
					if(response.matches("^have [a-f0-9]+ .*")){
						response = response.split(" ")[2];
						BufferMap recievedBufferMap = new BufferMap(_file.getBufferMap().getLength());
						recievedBufferMap.fillBufferMap(response.getBytes("ISO-8859-1"));
						
						_file.setDispo(recievedBufferMap);
					}
					s.close();
					_semaphore.release();
				}
				Thread.sleep(_intervalle*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
